package com.bawei.module_player

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.library_common.arouter.ARouterActivityPath
import com.bawei.library_common.bean.VideoHeaderBean
import com.bawei.library_common.mvvm.BaseMVVMActivity
import com.bawei.library_network.newFactory.ApiSuccessResponse
import com.bawei.library_video.helper.VideoPlayerHelper
import com.bawei.module_player.adapter.PlayerAdapter
import com.bawei.module_player.databinding.PlayerActivityPlayerBinding
import com.bawei.module_player.databinding.PlayerItemVideoHeaderViewBinding
import com.blankj.utilcode.util.ToastUtils
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/***
网络框架：
 专高一:httpUrlConnection
 专高二：Okhttp
 专高三/四：Retrofit+Okhttp+Rxjava(线程调度)
 专高五/六：Retrofit+Okhttp+LiveData(可观察数据，主线程获得数据)
 专高六：Retrofit+Okhttp+协程(优雅的实现异步任务)



 */
@Route(path = ARouterActivityPath.PAGER_PLAYER)
class PlayerActivity : BaseMVVMActivity<PlayerViewModel,PlayerActivityPlayerBinding>() {
    @Autowired
    lateinit var videoInfo:VideoHeaderBean //videoHeaderBean不能是私有的
    lateinit var orientationUtils: OrientationUtils //屏幕方向工具类

    private lateinit var playerAdapter: PlayerAdapter


    override fun getLayout(): Int {
       return R.layout.player_activity_player
    }

    override fun initData() {
        ARouter.getInstance().inject(this)//注入
        initStatusBar()//状态栏
        if(videoInfo != null){
            initView()//UI
            network()//网络请求数据
        }
    }

    private fun network() {
        //请求数据：livedata ，2个接口数据出现回调地狱
//            viewModel.video(videoInfo.videoId).observe(this){
//                when(it){
//                    is ApiSuccessResponse<PlayerEntity> -> {
//                        val itemList = it.body.itemList
//                        viewModel.comment(videoInfo.videoId).observe(this){
//
//                        }
//                    }
//                    else ->{
//
//                    }
//                }
//            }
        //请求数据，协程：2个接口
        lifecycleScope.launch(Dispatchers.Main) { //协程作用域
            //retrofit默认suspend方法在子线程中执行
            val videoList = viewModel.video(videoInfo.videoId).itemList
            val commentList = viewModel.comment(videoInfo.videoId).itemList
            //将2个集合合并一起
            val list =  ArrayList<PlayerEntity.Item>()
            list.addAll(videoList)
            list.addAll(commentList)
            //添加数据源
            playerAdapter.addData(list)
        }
    }

    //为状态栏预留空间
    private fun initStatusBar() {
        var height = geStatusBartHeight()
        var layoutParams = viewDataBinding.cvVideoView.layoutParams as ViewGroup.MarginLayoutParams
        layoutParams.topMargin = height
        viewDataBinding.cvVideoView.layoutParams = layoutParams
    }
    private fun initView() {
        //设置背景蓝红图
        viewDataBinding.blueredUrl = videoInfo.blurredUrl
        viewDataBinding.executePendingBindings()
        //设置视频播放器
        initVideo()
        //设置底部列表
        initRecyler()
    }

    private fun initRecyler() {
        playerAdapter = PlayerAdapter()
        viewDataBinding.rvVideoList.adapter = playerAdapter
        viewDataBinding.rvVideoList.setHasFixedSize(true)
        viewDataBinding.rvVideoList.layoutManager = LinearLayoutManager(this)
        playerAdapter.addHeaderView(getHeaderView())//头布局
        playerAdapter.addFooterView(getFootView()) //尾布局
    }
    //返回尾布局
    private fun getFootView(): View {
        return layoutInflater.inflate(R.layout.player_item_footer_white_view,viewDataBinding.rvVideoList,false)
    }

    //返回头布局并使用DataBinding绑定数据
    private fun getHeaderView(): View {
        var viewBinding =  DataBindingUtil.inflate<PlayerItemVideoHeaderViewBinding>(layoutInflater,R.layout.player_item_video_header_view,viewDataBinding.rvVideoList,false)
        if(videoInfo != null){
            viewBinding.videoInfo = videoInfo
        }
        return viewBinding.root
    }

    private fun initVideo() {

        viewDataBinding.cvVideoView.apply {
            //点击返回图标关闭页面
            backButton.setOnClickListener {
                finish()
            }
            //屏幕方向工具类 第一个this：上下文 第二个this是视频播放器
            orientationUtils = OrientationUtils(this@PlayerActivity, this)
            orientationUtils.isEnable = false //默认不能打开外部的旋转
            //初始化配置
            VideoPlayerHelper.optionPlayer(this, videoInfo.playerUrl, true, videoInfo.videoTitle)
            //上下滑动是否调整声音亮度，默认true
            setIsTouchWiget(true)
            setVideoAllCallBack(object : GSYSampleCallBack() {
                //准备好了
                override fun onPrepared(url: String?, vararg objects: Any?) {
                    super.onPrepared(url, *objects)
                    //打开外部的旋转
                    orientationUtils.isEnable = true
                }

                //退出全屏
                override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                    super.onQuitFullscreen(url, *objects)
                    orientationUtils.let {
                        it.backToProtVideo()
                    }
                }
            })

            //播放视频
            startPlayLogic()
        }
    }



    override fun initListener() {

    }

    override fun getJVMClass(): Class<PlayerViewModel> {
        return PlayerViewModel::class.java
    }


}